<?php
require_once "../lib/common.php";
$response = array();

if ( isset($_POST['update']) || isset($_POST['delete'])) {
    if ( isset($_POST['name']) ) {
        $_POST['name'] = htmlentities($_POST['name']);
    }
    $userLoggedIn = Login::getLoggedIn();
    if ($userLoggedIn == null) {
        error_die("access denied");
    }
    if ($userLoggedIn->admin != 1 && $userLoggedIn->employee != 1) {
        error_die("access denied");
    }

    if ( isset($_POST['update']) ) {
        if ( isset($_POST['id']) && !empty($_POST['id']) ) {
            $cat = BookCategory::find($_POST['id']);
            $ret = $cat->update_attributes_filter($_POST,$cat->attributes_but(array("created_at","updated_at")));
            if ($ret == false) {
                error_die('name '.$cat->errors->on("name"));
            }
        } else {
            $cat = new BookCategory();
            $ret = $cat->update_attributes_filter($_POST,$cat->attributes_but(array("created_at","updated_at")));
            if ($ret == false) {
                error_die('name '.$cat->errors->on("name"));
            }
        }
    } elseif ( isset($_POST['delete']) ) {
        $cat = BookCategory::find($_POST['id']);
        if (count($cat->books) == 0) {
            $cat->delete();
        } else {
            error_die("category not empty");
        }
    }
} else {
    $empty = new BookCategory();
    $response['attributes'] = array_keys($empty->attributes());
    unset($empty);
    $cat_collection = array();
    foreach (BookCategory::all() as $cat) {
        array_push($cat_collection,$cat->attributes());
    }
    $response['collection'] = $cat_collection;
}

if (!empty($response)) {
    echo json_encode($response);
}
?>
